<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属目录" prop="catelog">
         <el-select v-model="queryParams.catelog" placeholder="所属目录" clearable>
          <el-option
            v-for="dict in dict.type.file_catelog"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否删除" prop="delFlag">
         <el-select v-model="queryParams.delFlag" placeholder="是否删除" clearable>
          <el-option
            v-for="dict in dict.type.sys_del_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:file:add']"
        >新增</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
     
      <!-- <el-table-column label="类型，0文件，1富文本" align="center" prop="type" /> -->
      <el-table-column label="所属目录" align="center" prop="catelog" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.file_catelog" :value="scope.row.catelog"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip/>
      <el-table-column label="文件格式" align="center" prop="fileFormat" show-overflow-tooltip/>
       <el-table-column label="是否删除" align="center" prop="delFlag" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_del_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleContentView(scope.row)"
            v-hasPermi="['business:file:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:file:edit']"
            v-if="scope.row.delFlag =='0'"
          >修改</el-button>
          
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:file:remove']"
             v-if="scope.row.delFlag =='0'"
          >删除</el-button>

           <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleUpload(scope.row)"
            v-hasPermi="['business:file:upload']"
             v-if="scope.row.delFlag =='0'"
          >文件上传</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['business:file:download']"
             v-if="scope.row.delFlag =='0'"
          >文件下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属目录" prop="catelog">
          <el-select v-model="form.catelog" placeholder="请选择所属目录" :disabled="view">
                <el-option v-for="dict in dict.type.file_catelog" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="100" :disabled="view"/>
        </el-form-item>
        <!-- <el-form-item label="文件路径" prop="url">
          <el-input v-model="form.url" placeholder="请输入文件路径" />
        </el-form-item>
        <el-form-item label="是否删除，0正常，1删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入是否删除，0正常，1删除" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容" :disabled="view"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!view">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

      <!-- 附件导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
        <el-upload
        ref="upload"
        :limit="1"
        accept=".pdf,.docx,.txt"
        :headers="upload.headers"
        :action="upload.url + '?id=' + upload.id"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :before-upload="beforeUpload"
        drag
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div> -->
        <div class="el-upload__tip" style="color:red" slot="tip">提示：可以导入“docx”、“pdf”或“txt”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 预览 -->
      <el-dialog title="文件内容预览" :visible.sync="dialogVisible4" width="80%"  append-to-body center >
         <div style="max-height: 700px; overflow-y: auto;">
           <iframe :src="fileSrc" frameborder="0" style="width:100%;" height="500px" v-if="!isDocx"></iframe> 
          <!-- <div v-html="convertedHtml" /> -->
          <vue-office-docx :src="src" v-if="isDocx"/>
         </div>
      </el-dialog>
  </div>
</template>

<script>

import mammoth from "mammoth";
import VueOfficeDocx from "@vue-office/docx";

import { listFile, getFile, delFile, addFile, updateFile } from "@/api/business/file";
import { getToken } from "@/utils/auth";

export default {
  name: "File",
  dicts:['file_catelog','sys_del_flag'],
  components: {
    VueOfficeDocx
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件信息表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //view查看标志
      view:false,
      isDocx:false,//是否docx文件
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        catelog: null,
        title: null,
        url: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
         catelog: [
          { required: true, message: "所属目录不能为空", trigger: "blur" }
         ],
          title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
      },
       upload:{
         // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        updateSupport: 0,
        id: 0,//记录id
        isUploading: false,
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/file/upload"
      },
      //合同内容预览
      dialogVisible4: false,
      fileSrc: '', // 将从后台获取到的文件地址赋值给这个字段
      convertedHtml:''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件信息列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        catelog: null,
        title: null,
        url: null,
        status: null,
        delFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        updateBy: null
      };
      this.view = false;
      this.isDocx =false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除标题为"' + row.title + '"的数据项？').then(function() {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    handleUpload(row){
      this.upload.id = row.id;
       this.upload.title = "文件上传";
       this.upload.open = true;
    },
     // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.getList();
    },
    //文件上传前的校验
    beforeUpload(file){
        let filetype = file.name.substring(file.name.lastIndexOf('.')+1);
        if(!["docx","pdf","txt"].includes(filetype)){
          this.$modal.msgError("暂时只支持docx、pdf和txt格式的文件上传");
          return false;
        }
        return true;
    },

    //文件内容预览
    handleContentView(row){
      // this.reset();
      // const id = row.id || this.ids
      // getFile(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.view = true;
      //   this.title = "文件信息";
      // });

      let format = row.fileFormat;
      this.dialogVisible4 = true;
      if(format =='docx'){
        this.isDocx = true;
        this.src  = row.webUrl;
      }else{
        this.isDocx = false;
        this.fileSrc = row.webUrl;
      }

    },

    handleDownload(row){
      //window.open(row.webUrl);
      let a = document.createElement('a');
      a.href = row.webUrl;
      a.setAttribute('download','');
      a.click();
    }
  }
};
</script>

<style scoped>

</style>
